import OrgTree, { OrgTreeRefType } from '@/components/OrgTree';
import SearchTablePage, { SearchTablePageRefType } from '@/components/SearchTablePage';
import { PERMISSION_KEY_ORG } from '@/constants';
import {
  addOrg,
  deleteOrgById,
  deleteOrgsByIdList,
  getOrgByID,
  getOrgList,
  getOrgTrees,
  updateOrg,
} from '@/services/system/org';
import { checkRespSuccessful } from '@/utils/serviceUtils';

import { useModel } from '@umijs/max';
import { theme } from 'antd';
import { Key, useRef, useState } from 'react';

const Organization: React.FC = () => {
  const [selectParentIdList, setSelectParentIdList] = useState<Key[]>([]);
  const { useToken } = theme;
  const { token } = useToken();

  const { initialState } = useModel('@@initialState');
  const searchTablePageActionRef = useRef<SearchTablePageRefType>(null);
  const orgTreeActionRef = useRef<OrgTreeRefType>(null);

  return (
    <>
      <SearchTablePage<API.Org>
        tableName="机构"
        getRowById={getOrgByID}
        updateRow={updateOrg}
        addRow={addOrg}
        deleteRowById={deleteOrgById}
        deleteRowsByIdList={deleteOrgsByIdList}
        getRowsByPage={getOrgList}
        permissionKey={PERMISSION_KEY_ORG}
        onReset={() => {
          setSelectParentIdList([]);
          orgTreeActionRef.current?.refresh();
        }}
        onDeleted={(deleteIdList) => {
          setSelectParentIdList(selectParentIdList.filter((item) => !deleteIdList.includes(item)));
          orgTreeActionRef.current?.refresh();
        }}
        params={{
          id: selectParentIdList?.length > 0 ? selectParentIdList[0] : undefined,
        }}
        ref={searchTablePageActionRef}
        onAdd={() => {
          if (selectParentIdList.length > 0) {
            setTimeout(() => {
              searchTablePageActionRef.current?.setModalFormFieldValue(
                'parentId',
                selectParentIdList[0],
              );
            });
          }
        }}
        onAdded={() => {
          orgTreeActionRef.current?.refresh();
        }}
        onUpdated={() => {
          orgTreeActionRef.current?.refresh();
        }}
        columns={[
          {
            title: '机构 ID',
            dataIndex: 'id',
            hideInTable: true,
            hideInSearch: true,
            hideInModal: true,
          },
          {
            title: '机构编号',
            dataIndex: 'code',
            showDetail: true,
            rules: [{ required: true }],
          },
          {
            title: '机构名称',
            dataIndex: 'name',
            rules: [{ required: true }],
          },
          {
            title: '上级机构',
            dataIndex: 'parentId',
            valueType: 'treeSelect',
            allowClear: true,
            hideInSearch: true,
            fieldProps: {
              fieldNames: {
                value: 'id',
              },
            },
            modalFormTooltip: { title: '不选择机构则添加到根结点' },
            request: async () => {
              const res = await getOrgTrees();
              if (checkRespSuccessful(res)) {
                return res.data
                  ? [
                      {
                        id: 0,
                        label: '根机构',
                        children: res.data,
                      },
                    ]
                  : [];
              }
              return [];
            },
          },
          // {
          //   title: '上级机构名称',
          //   dataIndex: 'parentName',
          //   hideInModal: true,
          //   hideInSearch: true,
          // },
          {
            title: '机构地址',
            dataIndex: 'address',
            ellipsis: true,
            hideInSearch: true,
            hideInTable: true,
          },
          {
            title: '机构联系电话',
            dataIndex: 'phone',
            ellipsis: true,
            hideInTable: true,
            hideInSearch: true,
          },
          {
            title: '机构联系人',
            dataIndex: 'contact',
            ellipsis: true,
            hideInTable: true,
            hideInSearch: true,
          },
          {
            title: '状态',
            dataIndex: 'status',
            valueType: 'select',
            valueEnum: initialState?.system_common_status?.valueEnum,
            options: initialState?.system_common_status?.numOptions,
            rules: [{ required: true, message: '请选择状态' }],
          },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'dateTime',
            hideInSearch: true,
            hideInModal: true,
          },
        ]}
        leftSide={
          <OrgTree
            selectedKeys={selectParentIdList}
            onSelect={(selectedKeys) => {
              setSelectParentIdList(selectedKeys);
            }}
            ref={orgTreeActionRef}
            style={{
              flex: '0 0 auto',
              minWidth: 160,
              maxWidth: 260,
              overflow: 'auto',
              backgroundColor: token.colorBgContainer,
              paddingTop: token.paddingContentHorizontalLG,
              paddingBottom: token.paddingContentHorizontalLG,
              paddingLeft: token.padding,
              paddingRight: token.padding,
              borderRadius: token.borderRadius,
              borderWidth: 1,
              borderStyle: 'solid',
              borderColor: token.colorBorderSecondary,
            }}
          />
        }
      />
    </>
  );
};

export default Organization;
